作者:邱文馨4966 | 来源:互联网 | 2024-11-02 10:54
在处理多个玩家的相机控制时,我遇到了一个挑战,即无法在运行时动态添加播放器子对象以转换数组类型。为了解决这个问题,我在`CameraControl.cs`脚本中采取了临时措施。该脚本负责根据玩家的数量动态调整相机的缩放范围,确保所有玩家都能被相机捕捉到。
我对所有播放器使用以下相机脚本(链接)。脚本会放大和缩小以捕获所有玩家。游戏共有4位玩家。现在测试2。我无法使网络播放器的子对象(Kitty_Orange的变换)自动连接到摄像机。
子对象具有Player标记。
https://learn.unity.com/tutorial/camera-control?projectId=5c5149c5edbc2a001fd5be95#5c7f8528edbc2a002053b398
我有一个GameSetupController.cs,可将玩家实例化到场景中。这似乎是将化身的变换添加到相机的最合适的位置。当玩家进入游戏场景时,我会得到一个空引用。
尝试将变换动态添加到Camera m_Targets变换数组时出错。
已调试
Debug.Log("CC.m_Targets.Length" + CC.m_Targets.Length); //Troubleshooting
CC.m_Targets = new Transform[players.Length]; // array of size 1-4
NullReferenceException: Object reference not set to an instance of an object
GameSetupController.CreatePlayer () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:33)
GameSetupController.Start () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:14)
没有调试
CC.m_Targets = new Transform[players.Length]; // array of size 1-4
NullReferenceException: Object reference not set to an instance of an object
GameSetupController.CreatePlayer () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:34)
GameSetupController.Start () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:14)
Cameracontrol.cs
public Transform[] m_Targets; // All the targets the camera needs to encompass. [HideInInspector]
GameSetupController.cs
using Photon.Pun;
using System.IO;
using UnityEngine;
public class GameSetupController : MonoBehaviour
{
private Cameracontrol CC;
public GameObject[] players;
// This script will be added to any multiplayer scene
void Start()
{
CC = getcomponent();
CreatePlayer(); //Create a networked player object for each player that loads into the multiplayer scenes.
}
private void CreatePlayer()
{
Debug.Log("Creating Player");
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs","PhotonPlayer"),Vector3.zero,Quaternion.identity);
players = GameObject.FindGameObjectsWithTag("Player");
if (players.Length == 0)
{
return;
}
for (int i = 0; i {
Debug.Log("players.Length" + players.Length); //Troubleshooting
Debug.Log("CC.m_Targets.Length" + CC.m_Targets.Length); //Troubleshooting
CC.m_Targets = new Transform[players.Length]; // array of size 1-4
Debug.Log(CC.m_Targets.Length);
Debug.Log(players.Length);
CC.m_Targets[i] = players[i].transform;
Debug.Log("m_Targets : " + CC.m_Targets[i]);
Debug.Log("players : " + players[i]);
}
}
}
我的临时解决方案-在Cameracontrol.cs中
private void FixedUpdate()
{
m_Targets = new List();
//ADDS PLAYERS TO THE M_TARGETS LIST!
players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject child in players)
{
//Debug.Log(child.gameObject.transform.getchild(0));
m_Targets.Add(child.gameObject.transform.getchild(0));
}
您的CC对象为null,这是Null引用来自的地方。 GetComponent
将只找到与调用该脚本的脚本相同的GameObject附加的组件。如果在编辑器中将对象静态添加到场景,则可以使用[SerializeField]
属性使私有对象在检查器中可见,并手动分配引用。 Find
方法通常很昂贵,因此,如果您可以通过将引用存储在公共位置或事先进行设置来避免使用它们,则推荐使用这种方法。